package com.sino.operation.util;

import cn.hutool.json.JSONUtil;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.List;


public class JsonToObjectUtil {

    public static <T> List<T> toList(List<String> source, Class<T> clazz) {
        ArrayList<T> target = new ArrayList<>();
        if (!CollectionUtils.isEmpty(source)) {
            for (String s : source) {
                boolean jsonObj = JSONUtil.isJson(s);
                if (!jsonObj) {
                    return null;
                } else {
                    T t = JSONUtil.toBean(s, clazz);
                    target.add(t);
                }
            }
            return target;
        }
        return null;
    }

    public static <T> T toObject(String jsonStr, Class<T> clazz) {
        if (jsonStr == null) {
            return null;
        }
        T obj = null;
        if (!JSONUtil.isJson(jsonStr)) {
            return null;
        }
        try {
            obj = JSONUtil.toBean(jsonStr, clazz);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return obj;
    }
}